package logic

import (
	"common"
	"common/grpcx"
	"common/zapx"
	"gateway/internal/pb"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"time"
	"wrong"
)

type BookLogic struct {
	BaseLogicAbs
}

// NewBookLogic 创建图书逻辑对象
func NewBookLogic() *BookLogic {
	logic := BookLogic{
		BaseLogicAbs{
			message: "",
		},
	}
	return &logic
}

// FavouriteAction 收藏漫画动作
func (bl *BookLogic) FavouriteAction(ginCtx *gin.Context, comicId int32) (operate int32, ok bool) {
	conn, err := grpcx.NewNoCertConn("book")
	if err != nil {
		zapx.Logger.Error("链接[book]服务失败", zap.Error(err))
		return 0, bl.setMessage("系统内部错误")
	}
	defer conn.Close()
	client := pb.NewBookClient(conn)
	ctx, cancel := common.WithMetaDataOutGoingTimeoutContext(time.Second*2, grpcx.GetUserMetaData(ginCtx))
	defer cancel()
	res, err := client.Favourite(ctx, &pb.FavouriteRequest{
		ComicId: comicId,
	})

	if err != nil {
		return 0, bl.setMessage(grpcx.GetGrpcErrorMessage(err))
	}

	return res.Operate, true
}

// GetListByPage 获取收藏的漫画，分页
func (bl *BookLogic) GetListByPage(ginCtx *gin.Context, page *int32, perPage *int32) (*pb.IndexResponse, error) {
	conn, err := grpcx.NewNoCertConn(
		"book",
	)
	if err != nil {
		zapx.Logger.Error("连接到 book 服务失败", zap.Error(err))
		return nil, wrong.GRPC_CONN_FAILED
	}
	defer conn.Close()
	call := pb.NewBookClient(conn)
	ctx, cancel := common.WithMetaDataOutGoingTimeoutContext(time.Second*2, grpcx.GetUserMetaData(ginCtx))
	defer cancel()
	res, err := call.Index(ctx, &pb.IndexRequest{
		Page:    page,
		PerPage: perPage,
	})
	if err != nil {
		return nil, grpcx.CovertGrpcError(err)
	}
	return res, nil
}
